<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Data extends ApiHomeController {

    private $CI;
	function __construct() { 
		parent::__construct();
	
        $this->CI = &get_instance();
		$this->CI->load->model('Class_model');
	}

    public function  berger_test()
    {
        
       
        $curl = curl_init();

        // $start = microtime(true);
        
       
        $post_body = '{
            "tag": 831,
            "current": 1,
            "size": 10000,
            "search" : "",
            "isAsc":"1",
            "orderBy":""
        }';

        $token = $this->get_token();



        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt_array($curl, [
        CURLOPT_URL => "https://dsc.zjipc.cn/sjztng/openApi/data/getOpenDataList/v2?token=".$token,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $post_body,
        CURLOPT_SSL_VERIFYPEER =>false,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "cache-control: no-cache",
            "token: 4bd26f8022ea1c1a96bd9c7693a65d7c5a0b39fcf3e08d6eff174dd6e823a5b3"
        ]
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            // echo "cURL Error #:" . $err;
            // return  ['msg' =>'error','code' => 599];
            echo json_encode(['msg' =>'error','code' => 599]);
        } else {
            // 接口返回

            // $class=$this->CI->Class_model->get_single_full($connar);
            // TRUNCATE TABLE 表名;
            // 构建TRUNCATE表的SQL语句
            $sql_clear = "DELETE FROM db_class WHERE elective_lesson_no ='(2024-2025-2)';";
        
            // 执行SQL语句
            $this->db->query($sql_clear);

           $res = json_decode($response, true);

        //    var_dump($res['result']['records']);
         
           $insert_info_arr = [];
           foreach($res['result']['records'] as $value){

                // var_dump($value);
                //
                $new_lesson_code = substr($value['xkkh'],0,20);
             

                    switch ($value['xqj']) {
                        case '1':
                        $xqj = '一';
                            break;
                        case '2':
                            $xqj = '二';
                            break;
                        case '3':
                            $xqj = '三';
                            break;
                        case '4':
                            $xqj = '四';
                            break;
                        case '5':
                            $xqj = '五';
                        break;
                        case '6':
                            $xqj = '六';
                        break;
                        case '7':
                            $xqj = '日';
                        break;
                        default:
                            # code...
                            break;
                    }
                    
                    if( isset($insert_info_arr[ $new_lesson_code])){

                        
                        if($insert_info_arr[$new_lesson_code]['start_time'] ==  $value['zc']  &&
                        $insert_info_arr[ $new_lesson_code]['classroom'] ==  $value['xqu'].'-'. $value['skdd'] 
                
                        ) {
                            $insert_info_arr[$new_lesson_code]['sksj'] .= ';周'.$xqj.'第'.$value['jc'].'节{'. $value['zc'].'}';
                            $insert_info_arr[ $new_lesson_code]['class_xqj'] .= '-'.$xqj ;
                        } else {
                            $insert_info = [];

                            $insert_info = array(
                                'code' => $value['kcdm'],// 课程代码
                                'name' => $value['kcmc'],
                                'elective_lesson_no' => '('.$value['xn'].'-'.$value['xq'].')',//选课课号
                                'teaching_plan_no' => '',//教学计划号
                                'professional_direction' => '',//专业方向
                                'start_time' => $value['zc'],//开始时间
                                'end_time' => $value['zc'],//结束时间
                                'teacher_id' => $value['skjsgh'],//teacher id
                                'teacher_name' => $value['skjsxm'],//teacher id
                                
                                'course_units' => $value['kkbm'],//开课单位
                                'classroom' =>  $value['xqu'].'-'. $value['skdd'],//教室
                                'classname' =>  $value['skbj'],//班级
                                'type' => '公共基础课',//类型
                                'creator' => '',//创建人
                                'updator' => '',//更新人
                                'created' => '',//创建
                                'updated' => time(),//更新
                                'lesson_code' => $new_lesson_code,//更新
                                'class_xqj' =>$xqj,//更新
                                
                            
                                'sksj' => '周'.$xqj.'第'.$value['jc'].'节{'. $value['zc'].'}',//上课时间
                            );
                            $insert_info_arr[ $new_lesson_code.rand(100,999)] = $insert_info;
                        }

                        
                    } else {
                
                        $insert_info = [];


                        // $str =  '2A0EC28ACE5F2F7EE065000000000001';
                        // $new_lesson_code = substr($value['xkkh'],,0,20);
                       

                        $insert_info = array(
                            'code' => $value['kcdm'],// 课程代码
                            'name' => $value['kcmc'],
                            'elective_lesson_no' => '('.$value['xn'].'-'.$value['xq'].')',//选课课号
                            'teaching_plan_no' => '',//教学计划号
                            'professional_direction' => '',//专业方向
                            'start_time' => $value['zc'],//开始时间
                            'end_time' => $value['zc'],//结束时间
                            'teacher_id' => $value['skjsgh'],//teacher id
                            'teacher_name' => $value['skjsxm'],//teacher id
                            
                            'course_units' => $value['kkbm'],//开课单位
                            'classroom' =>  $value['xqu'].'-'. $value['skdd'],//教室
                            'classname' =>  $value['skbj'],//班级
                            'type' => '公共基础课',//类型
                            'creator' => '',//创建人
                            'updator' => '',//更新人
                            'created' => '',//创建
                            'updated' => time(),//更新
                            'lesson_code' => $new_lesson_code,//更新
                            'class_xqj' =>$xqj,//更新
                            
                        
                            'sksj' => '周'.$xqj.'第'.$value['jc'].'节{'. $value['zc'].'}',//上课时间
                        );
                        $insert_info_arr[ $new_lesson_code] = $insert_info;
                    }
                
               
            
                
            }
         
            // var_dump($insert_info_arr);

            foreach ($insert_info_arr as $item) {
                $this->db->insert('db_class', $item);
            }
            
        }

         // 运行你的代码
         echo json_encode(['msg' =>'success','code' => 200]);
        
        //  $end = microtime(true); 
        //  $executionTime = $end - $start;
          
        //  echo "代码运行时间为：{$executionTime} 秒";
    }


    private function get_token()
    {
       

        $curl = curl_init();

        curl_setopt_array($curl, [
        CURLOPT_URL => "https://dsc.zjipc.cn/sjztng/openApi/token?compId=f39a938e6ea83337872e158171322797&appId=xydxlxqg269vw7y4e4ydgr9gqqvgi1w1&appSecret=tBxPTmO6iVjeFitGJWztF9IRu8m4STL1Xkq4ZWEPEA93xZgn6yuNVLP_KHibXMip",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_SSL_VERIFYPEER =>false,
        CURLOPT_HTTPHEADER => [
            "cache-control: no-cache"
        ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
        echo "cURL Error #:" . $err;exit;
        } else {
            $res = json_decode($response, true);

            if($res['success']  == true ) {
                return  $res['result']['access_token'];
            }
            
        
        }
        echo 'done';
    }
 }

